#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <assert.h>
#include <sys/socket.h>

#define MAXSIZE 512

int main(int argc, char **argv) {
    if (argc != 2) {
        printf("usage %s <broadcast_port>\n", argv[0]);
        return 0;
    }
    struct sockaddr_in addr;
    int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
    assert(sockfd != -1);

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY); 
    addr.sin_port = htons(atoi(argv[1]));

    int rc = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    assert(rc != -1);
 
    char recvbuff[MAXSIZE] = {0};

    while (1) {
        int strlen = recvfrom(sockfd, recvbuff, MAXSIZE, 0, NULL, 0);
        printf("strlen = %d\n", strlen);
        if (strlen == 0)
            break;
        recvbuff[strlen] = 0;
        printf("%s\n", recvbuff);
    }
    close(sockfd);
    return 0;
}